package com.imooc.mail.controller;

import com.imooc.mail.consts.MallConst;
import com.imooc.mail.form.UserLoginForm;
import com.imooc.mail.form.UserRegisterForm;
import com.imooc.mail.pojo.User;
import com.imooc.mail.service.IUserService;
import com.imooc.mail.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @Author wjc
 * Date on 2020/6/4 22:21
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService iUserService;

    @PostMapping("/register")
    public ResponseVo<User> register(@Valid @RequestBody UserRegisterForm userRegisterForm) {
        // 进行注册
        User user = User.builder().build();
        BeanUtils.copyProperties(userRegisterForm, user);


        return iUserService.register(user);
    }

    @PostMapping("/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
//                            HttpServletRequest httpServletRequest,
                            HttpSession session
    ) {
        // 进行注册
        User user = User.builder().build();
        BeanUtils.copyProperties(userLoginForm, user);

        ResponseVo<User> userResponseVo = iUserService.login(user);
        session.setAttribute(MallConst.CURRENT_USER, userResponseVo.getData());

        return userResponseVo;
    }

    @PostMapping("/logout")
    public ResponseVo<User> logout(HttpSession session) {
        // 打印日志
        log.info("/user/logout sessionId={}",session.getId());
        // 判断登录状态，用拦截器
        // 抹去session
        session.removeAttribute(MallConst.CURRENT_USER);

        return ResponseVo.success();
    }

    @GetMapping
    public ResponseVo<User> getUserInfo(HttpSession session) {
        // 判断登录状态，用拦截器
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success(user);
    }


}
